package com.frame.security.service.handle;

import com.frame.common.core.entity.SysUser;
import com.frame.common.enums.UserStatus;
import com.frame.common.core.security.entity.SecurityUser;
import com.frame.exception.CustomException;
import com.frame.security.service.ISysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private ISysUserService userService;
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            throw new CustomException("账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new CustomException("账号：" + username + " 已停用");
        }
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        return new SecurityUser(user,menuPermission);
    }
}
